<template>
  <div class="cosmetology">
  	<div class="cosheader">
	    <x-header title="洗车美容" :left-options="{backText:''}" class='whiteHeader'></x-header>
	    <div class="tabs">
        <div class="tabItem" @click='changeArea'>
          <label :class='{activeLabel:active1}'>{{area}}
          </label>
          <span :class='{on:active1}'></span>
        </div>
        <div class="tabItem" @click='changeClass'>
          <label :class='{activeLabel:active2}'>{{classs}}
          </label>
          <span :class='{on:active2}'></span>
        </div>
        <div class="tabItem" @click='changeOrderBy'>
         <label :class='{activeLabel:active3}'>{{orderBy}}</label>
         <span :class='{on:active3}'></span>
        </div>
	    </div>
      <div class="selects" v-if='showSelect'>
        <ul>
          <li v-for='item in showArr' @click='selectItem(item)'>
            <span v-if='item.NAME' :class='{spanActive:item.flag==1}'>{{item.NAME}}</span>
            <span v-if='item.SERV_NAME' :class='{spanActive:item.flag==1}'>{{item.SERV_NAME}}</span>
            <span v-if='item.value' :class='{spanActive:item.flag==1}'>{{item.value}}</span>
          <div class="noSelect" :class='{select:item.flag==1}'></div></li>
        </ul>
      </div>
    </div>
    <div class="cosMain">
      <scroller :on-infinite="infinites" class='myScroller' ref='myScroller' :loadingLayerColor='loadColor'>
      <div class="allStore">
          <div class="Store" v-for='item in shopMess.RESULT_DATA'>
            <div class="storeMess" @click='goStoreDetail(item.COMP_ID,item.COORDINATE)'>
              <img :src="shopMess.PHOTO_URL+item.SHOP_PHOTO" alt="" />
              <div class="storeIntro">
                <h2>{{item.SHOP_NAME}}</h2>
                <p class="storeAddress">{{item.SHOP_ADDRESS}}</p>
                <p class="storePrice">营业时间：{{item.SERV_START_TIME}}-{{item.SERV_END_TIME}}</p>
              </div>
              <div class="distance">{{(item.DISTANCE/1000).toFixed(2)}}Km</div>
            </div>
            <ul>
              <li v-for='items in item.SERVS' class="classItem">
                <div class="showDetailTop" @click='goShopDetail(items.SERV_ID)'>
                  <h1>{{items.SERV_SUBJECT}}</h1>
                  <p>适用车型：{{items.USE_CAR_RANGE}}</p>
                </div>
                <div class="showDetailBottom">
                  <p><s>￥{{items.ORIGINAL_PRICE}}</s><span>￥{{items.PRICE}}</span></p>
                  <div class="btns" @click='downOrder(item,items)'>
                    下单
                  </div>
                </div>
              </li>
            </ul>
          </div>
      </div>
      </scroller>
    </div>
  </div>
</template>
<script>
/*美容*/
import {XHeader,Selector,Group} from 'vux';
import { setCookie, getCookie } from '../../util/commonUtils';
import { deviceLocation } from '../../util/baidumap';
import axios from 'axios'
export default {
  name:"cosmetology",
  // 数据
  data(){

    return{
    	userId:'',
    	area:'区域',//区域
    	classs:'类型',//类型
    	orderBy:'排序',  //排序
      classCos:{
        areaList:[],
        classsList:[],
        orderByList:[{value:'价格最低',key:1,flag:0},{value:'距离最近',key:2,flag:1},{value:'评分最高',key:3,flag:0}]
      },
      shopMess:'', //商店数据
      requestObj:{
        CITY:'深圳',
        REGION:'南山',
        COORDINATE:'114.02597366,22.54605355',
        CLASS_ID:'',
        SORTING:'2',
        PAGE_NO:1,
        PAGE_SIZE:4
      },  //请求参数
      flag:false,  //控制请求
      showSelect:false,
      showArr:[],
      active1:false, //控制排序的三个箭头变化
      active2:false, 
      active3:false,
      carFlag:false, //判断用户是否有车辆信息
      loadColor:'#efeff4'
    }
  },
  // 计算属性
  computed:{

  },
  // 导航离开该组件的对应路由时调用
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    this.$vux.loading.hide();
    next();
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if(!from.name){
        if(vm.$route.query.city){
          let id=vm.$route.query.id;
          vm.init(id);
        }else{
          vm.locations();
        }
      }else{
        let id=vm.$route.query.id;
        vm.init(id);
      }
    })
  },
  // 创建（实例创建完成）
  created(){
    this.userId=getCookie('loginkey');
    //获取所有区域
    //获取汽车美容的种类
    let that=this;
    this.$vux.loading.show({
       text: ''
    });
    this.getUserCar();
  },
  // el被创建，并挂载到实例上
  mounted(){

  },
  // 方法（实例中的方法）-----------
  methods:{
    locations(){
      let that = this;
      // let geolocation = new BMap.Geolocation();
      // geolocation.getCurrentPosition(function(r){
      //   if(this.getStatus() == BMAP_STATUS_SUCCESS){
      //     let lng = r.point.lng;//经度
      //     let lat = r.point.lat;//纬度
      //     let latlgt=lng+","+lat;
      //     let city=r.address.city.slice(0,r.address.city.length-1);
      //     sessionStorage.setItem('latlgt',latlgt);
      //     sessionStorage.setItem('city',city);
      //     that.getAddress(city);
      //   }
      //   else {
      //     alert('定位失败');
      //   }        
      // },{enableHighAccuracy: true})
      deviceLocation().then((data) => {
        // 获取百度定位后信息
        if(data.result.addressComponent.city){
          let city = data.result.addressComponent.city.slice(0,data.result.addressComponent.city.length-1);
          let lng = data.result.location.lng;//经度
          let lat = data.result.location.lat;//纬度
          let latlgt=lng+","+lat;
          sessionStorage.setItem('latlgt',latlgt);
          sessionStorage.setItem('city',city);
          that.getAddress(city);
        }else{
          let lng ='113.937737';
          let lat = '22.554592';
          let latlgt=lng+","+lat;
          let city='深圳';
          sessionStorage.setItem('latlgt',latlgt);
          sessionStorage.setItem('city',city);
          that.getAddress(city);
        }
      })
    },
    //获取区域列表
    getAddress(city){
        this.$fetchPost('/CommonServiceWeb/getRegion.action',{CITY_ID:0}).then(res=>{
          if(res.STATUS_CODE==1){
            let allCity=res.RESULT_DATA;
            let flag=false;
            let selectCity='';
            for(let i=0;i<allCity.length;i++){
              if(allCity[i].NAME==city){
                flag=true;
                if(!allCity[i].WASH){
                  sessionStorage.setItem('city','深圳');
                }
              }
            }
            if(!flag){
              sessionStorage.setItem('city','深圳');
            }
            for(let i=0;i<allCity.length;i++){
              if(allCity[i].NAME==sessionStorage.getItem('city')){
                selectCity=allCity[i];
              }
            }
            this.init(selectCity.ID);
          }
        },err=>{
          console.log(err);
        })
    },
    init(id){
      let that=this;
      this.$getAll({CITY_ID:id},{PARENT_ID:'10002'}).then(axios.spread(function (acct, perms) {
        if(acct.data.STATUS_CODE==1){
          let arr=acct.data.RESULT_DATA;
          for(let i=0;i<arr.length;i++){
            arr.flag=0;
          }
          arr.unshift({ID: "0", NAME: "全部", INITIAL: "N", ORDER_NUM: 1, IS_HOT: "0", WASH: "", MAINTAIN: "", SPRAY: "",WASH:'',flag:1});
          that.classCos.areaList=arr;
          that.requestObj.REGION='';
        }
        if(perms.data.STATUS_CODE==1){
          let arr=perms.data.RESULT_DATA;
          for(let i=0;i<arr.length;i++){
            arr.flag=0;
          }
          arr.unshift({SERV_ID: '', SERV_NAME: "全部", ORDER_NUM: 0, ICON_NAME: "",flag:1});
          that.classCos.classsList=arr;
        }
        that.getCosMess();
      })
      )
    },
    //区域改变
    changeArea(){
      if(this.active2){
        this.active2=false;
        this.showSelect=false;
      }
      if(this.active3){
        this.active3=false;
        this.showSelect=false;
      }
      this.showSelect=!this.showSelect;
      this.active1=!this.active1;
      this.showArr=this.classCos.areaList;
    },
    //美容种类的改变
    changeClass(){
      if(this.active1){
        this.active1=false;
        this.showSelect=false;
      }
      if(this.active3){
        this.active3=false;
        this.showSelect=false;
      }
      this.showSelect=!this.showSelect;
      this.active2=!this.active2;
      this.showArr=this.classCos.classsList;
    },
    //排序
    changeOrderBy(){
      if(this.active2){
        this.active2=false;
        this.showSelect=false;
      }
      if(this.active1){
        this.active1=false;
        this.showSelect=false;
      }
      this.showSelect=!this.showSelect;
      this.active3=!this.active3;
      this.showArr=this.classCos.orderByList;
    },
    //选择不同的查询条件
    selectItem(item){
      if(this.active1){
        for(let i=0;i<this.classCos.areaList.length;i++){
          this.$set(this.classCos.areaList[i],'flag',0);
          if(item.ID==this.classCos.areaList[i].ID){
            this.$set(this.classCos.areaList[i],'flag',1);
            if(item.NAME==='全部'){
              this.requestObj.REGION='';
            }else{
              this.requestObj.REGION=item.NAME;
            }
            this.area=item.NAME;
          }
        }
        this.active1=!this.active1;
      }else if(this.active2){
        for(let i=0;i<this.classCos.classsList.length;i++){
          this.$set(this.classCos.classsList[i],'flag',0);
          if(item.SERV_ID==this.classCos.classsList[i].SERV_ID){
            this.$set(this.classCos.classsList[i],'flag',1);
            this.classs=item.SERV_NAME;
            this.requestObj.CLASS_ID=item.SERV_ID;
          }
        }
        this.active2=!this.active2;
      }else if(this.active3){
        for(let i=0;i<this.classCos.orderByList.length;i++){
          this.$set(this.classCos.orderByList[i],'flag',0);
          if(item.value==this.classCos.orderByList[i].value){
            this.$set(this.classCos.orderByList[i],'flag',1);
            this.orderBy=item.value;
            this.requestObj.SORTING=item.key;
          }
        }
        this.active3=!this.active3;
      }
      this.flag=false;
      this.getCosMess();
      this.requestObj.PAGE_NO=1;
      this.showSelect=!this.showSelect;
    },
    getCosMess(){
      this.loadColor='#efeff4';
      this.$vux.loading.show({
       text: ''
      });
      this.requestObj.CITY=sessionStorage.getItem('city');
      this.requestObj.COORDINATE=sessionStorage.getItem('latlgt');
      this.$fetchPost('/ServDetailWeb/getBeautyList.action',this.requestObj).then(res=>{
        if(res.STATUS_CODE==1){
          this.shopMess=res;
          this.requestObj.PAGE_NO++;
          this.flag=true;
          this.$vux.loading.hide();
          this.$refs.myScroller.finishInfinite();//通知scroller数据已经加载完成
        }
      },err=>{
        console.log(err);
      })
    },
    //下拉加载更多
    infinites(){
      if(!this.flag){
        return;
      }
      this.loadColor='#aaa';
      this.$fetchPost('/ServDetailWeb/getBeautyList.action',this.requestObj).then(res=>{
        if(res.STATUS_CODE==1){
          this.shopMess.RESULT_DATA=this.shopMess.RESULT_DATA.concat(res.RESULT_DATA);
          if(res.RESULT_DATA.length==0){
            this.$refs.myScroller.finishInfinite(2);
            return;
          }else{
            this.$refs.myScroller.finishInfinite();//通知scroller数据已经加载完成
          }
          this.requestObj.PAGE_NO++;
        }
      },err=>{
        console.log(err);
      })
    },
    //去4s门店详情
    goStoreDetail(id,COORDINATE){
      this.$router.push('/storeDetail/'+id+'?coordinate='+COORDINATE);
    },
    //去商品详情
    goShopDetail(id){
      this.$router.push('/shopDetail/'+id);
    },
    checkedOrder(){
      let that=this;
      if(this.userId){
        return true;
      }else{
        this.$vux.confirm.show({
          title:'提示',
          content:'请先登录',
          onConfirm () {
            that.$router.push('/login');
          }
        })
        return false;
      }
      if(this.carFlag){
        this.$vux.confirm.show({
          title:'提示',
          content:'请先添加车辆',
          onConfirm () {
            localStorage.setItem("addCar",JSON.stringify({}));
            localStorage.setItem('carFrom','cosmetology');//代表来自美容没有车辆时添加车辆
            // 标识将跳回选择车辆
            localStorage.removeItem('selectCars');
            localStorage.removeItem('editCar');
            this.$router.push('/addCar');
          }
        })
        return false;
      }else{
        return true;
      }
    },
    getUserCar(){
      //获取用户所有车辆
      this.$fetchGet('/UserWeb/getCars.action',{USER_ID:this.userId}).then(res=>{
        if(res.STATUS_CODE==1){
           if(res.CARS.length==0){
              this.carFlag=true;
           }else{
              this.carFlag=false;
           }
        }
      },err=>{
        console.log(err);
      })
    },
    //下单
    downOrder(item,items){
      if(!this.checkedOrder()){
        return;
      }
      let obj={};
      obj.USER_ID=this.userId;
      obj.ORDER_LIST=[];
      let objs={};
      objs.COMP_ID=item.COMP_ID;
      objs.SHOP_NAME=item.SHOP_NAME;
      objs.SERV_PARAMS=[];
      let objss={};
      objss.SERV_ID=items.SERV_ID;
      objss.SERV_FIRST_CLASS=items.SERV_FIRST_CLASS;
      objss.SERV_SECON_CLASS=items.SERV_SECON_CLASS;
      objss.SUPP_CASH_VOL=items.SUPP_CASH_VOL;
      objss.SUPP_DIS_VOL=items.SUPP_DIS_VOL;
      objss.SUPP_NOR_CASH_VOL=items.SUPP_NOR_CASH_VOL;
      objss.PRICE=items.PRICE;
      objss.SERV_SUBJECT=items.SERV_SUBJECT;//商品名称
      objss.QUANTITY=1;
      objss.ATTR_LIST=[];
      objs.SERV_PARAMS.push(objss);
      obj.ORDER_LIST.push(objs);
      // 清除订单页支付来自哪里的数据
      localStorage.removeItem('from');
      //清除支付页的数据
      sessionStorage.removeItem('orderMess');
      //支付数据
      sessionStorage.setItem('shopMess',JSON.stringify(obj));
      this.$router.push('/shopPay');
    }
  },
  // 子组件
  components:{
    XHeader,Selector,Group
  }
}
</script>
<!--当前页面的样式 -->
<style lang="less" scoped>
@import url('../../assets/css/public.less');
.cosmetology{
  width: 7.5rem;
  background: #fff;
  .tabs{
  	display: flex;
    height: 0.8rem;
    background: #fff;
    padding: 0.15rem 0;
  	>div{
  		width: 33.3%!important;
  	}
    .tabItem{
      display: flex;
      justify-content:center;
      align-items:center;
      label{
        font-size: 0.25rem;
        line-height: 0.5rem;
      }
      .activeLabel{
        color: #ec2121;
      }
      span{
        width: 0.18rem;
        height: 0.11rem;
        margin-left: 0.1rem;
        background: url('../../assets/image/home/down.png') no-repeat;
        background-size: 0.18rem 0.11rem;
      }
      .on{
        background: url('../../assets/image/home/up.png') no-repeat;
        background-size: 0.18rem 0.11rem;
      }
      select{
        appearance:none;
        border:0;
        opacity: 0;
        width: 100%;
        height: 100%;
        -moz-appearance:none;
        -webkit-appearance:non;
        option{
          padding: 0.1rem;
        }
      }
    }
    .tabItem:nth-child(1),.tabItem:nth-child(2){
      .borderRFu(#ede9e9);
    }
    .borderBFu(#ede9e9);
  }
  .selects{
    position: absolute;
    top: 1.6rem;
    background: #fff;
    height: auto;
    width: 100%;
    max-height: 7rem;
    overflow: scroll;
    box-shadow: 0 6px 5px rgba(0,0,0,.06);  
    li{
      font-size: 0.25rem;
      height: 0.7rem;
      line-height: 0.7rem;
      .borderBFu(#ede9e9);
      display:flex;
      padding: 0 0.2rem 0 0.3rem;
      justify-content:space-between;
      align-items:center;
      .spanActive{
        color: #ec2121;
      }
    }
    .noSelect{
      width: .33rem;
      height: 0.22rem;
    }
    .select{
      background: url('../../assets/image/home/select.png') no-repeat;
      background-size: 0.33rem 0.22rem;
    }
  }
  .cosheader{
    position: fixed;
    top: 0;
    width: 7.5rem;
    height: 1.6rem;
    z-index: 666;
  }
  .allStore{
    padding-top: 1.6rem;
  }
  .Store{
    
      background: white;
      border-bottom:.22rem solid #eee;
      //box-shadow: 0 0 10px #ddd;
      box-sizing: content-box;
  }
  .Store:last-child{
     border-bottom: 0;
  }
  .storeMess{
    display: flex;
    padding: .29rem .10rem .29rem .29rem;
    height: 2rem;
    box-sizing: border-box;
    .borderBFu(#ede9e9);
  }
  .storeMess img{
    height: 1.26rem;
    width: 1.26rem;
    min-width: 1.26rem;
    border-radius: .08rem;
    margin-top: 0.08rem;
  }
  .storeMess .storeIntro{
    width:4.5rem;
    margin: 0 .2rem 0 .2rem;
    text-align: left;
  }
  .storeMess .storeIntro h2{
    font-size: .3rem;
    margin-bottom: .1rem;
    font-weight: bold;
    color: #000;
  }
  .storeMess .storeIntro p.storeAddress{
    font-size: .24rem;
    height: 0.6rem;
    color: #bcbcbc;
    overflow:hidden;
    text-overflow:ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .storeMess .storeIntro p.storePrice{
    color: #8c8c8c;
    font-size: .24rem;
    em{
      font-size: .23rem;
      font-weight: normal;
    }
  }
  .storeMess .distance{
    width: 1.19rem;
    text-align: center;
    line-height: 1.5rem;
    font-size: .27rem;
    color: #b7b5b5;
  }
  .classItem{
    padding: 0.1rem 0.3rem;
    .borderBFu(#ede9e9);
    display: flex;
    justify-content: space-between;
    align-items:center;
    height: 1.3rem;
    .showDetailTop{
      height: 0.7rem;
      text-align: left;
      h1{
        font-size: 0.28rem;
        color: #030303;
        margin-bottom: 0.2rem;
      }
      p{
        font-size: 0.23rem;
        color: #8c8c8c;
      }
    }
    .showDetailBottom{
      overflow: hidden;
      p{
        font-size: 0.28rem;
        s{
          font-size: 0.2rem;
        }
        span{
          color: #f31616;
          padding-left: 0.1rem;
        }
      }
      .btns{
        font-size: 0.27rem;
        width: 1.2rem;
        margin-top: 0.1rem;
        height: 0.55rem;
        line-height: 0.6rem;
        color: #fff;
        background: #e71928;
        border-radius: 0.15rem;
        float: right;
      }
    }
  }
}
</style>